package service

import (
	"context"
	"onvif_server/api/subscription"
	"onvif_server/internal/model"
	"onvif_server/internal/repository"
	"onvif_server/pkg/subscribe"
)

type SubscriptionService interface {
	List(ctx context.Context, req *subscription.ListReq) (total int64, res []*model.Subscription, err error)
	Create(ctx context.Context, req *subscription.CreateReq) error
	Update(ctx context.Context, req *subscription.UpdateReq) error
	Delete(ctx context.Context, ids []int) error
	//Topics 告警事件
	Topics(ctx context.Context) any
	//Test 模拟推送订阅，用于测试
	Test(ctx context.Context, req *subscription.TestReq) error
}

func NewSubscriptionService(service *Service, subRepo repository.SubscriptionRepository, subLib *subscribe.Subscribe) SubscriptionService {
	return &subscriptionService{
		Service: service,
		subRepo: subRepo,
		subLib:  subLib,
	}
}

type subscriptionService struct {
	subRepo repository.SubscriptionRepository
	subLib  *subscribe.Subscribe
	*Service
}

func (s *subscriptionService) List(ctx context.Context, req *subscription.ListReq) (total int64, res []*model.Subscription, err error) {
	return s.subRepo.List(ctx, "", req.PageQuery())
}

func (s *subscriptionService) Create(ctx context.Context, req *subscription.CreateReq) error {
	m := model.Subscription{}
	m.AppName = req.AppName
	m.AppKey = req.AppKey
	m.ApiUrl = req.ApiUrl
	m.Remark = req.Remark
	m.Topics = req.Topics
	return s.subRepo.Create(ctx, &m)
}

func (s *subscriptionService) Update(ctx context.Context, req *subscription.UpdateReq) error {
	m, err := s.subRepo.GetByID(ctx, req.ID)
	if err != nil {
		return err
	}
	m.AppName = req.AppName
	m.AppKey = req.AppKey
	m.ApiUrl = req.ApiUrl
	m.Remark = req.Remark
	m.Topics = req.Topics
	return s.subRepo.Update(ctx, m, req.Fields()...)
}

func (s *subscriptionService) Delete(ctx context.Context, ids []int) error {
	return s.subRepo.DeleteByIDs(ctx, ids)
}

func (s *subscriptionService) Topics(ctx context.Context) any {
	return []subscription.Kv{
		{
			Label: "告警信息",
			Value: subscribe.TopicAlarm,
		},
		{
			Label: "添加摄像头",
			Value: subscribe.TopicCameraCreate,
		},
		{
			Label: "摄像头信息",
			Value: subscribe.TopicCameraInfo,
		},
		{
			Label: "移除摄像头",
			Value: subscribe.TopicCameraRemove,
		},
		{
			Label: "摄像头在线状态",
			Value: subscribe.TopicCameraOnline,
		},
	}
}

// Test 测试
func (s *subscriptionService) Test(ctx context.Context, req *subscription.TestReq) error {
	ap := subscribe.AlarmPayload{ID: 2, DeviceId: "test_device_id", Status: 1, Remark: "测试推送预警消息"}
	m, err := s.subRepo.GetByID(ctx, req.ID)
	if err != nil {
		return err
	}
	return s.subLib.Push([]subscribe.Subscriber{{Url: m.ApiUrl, Key: m.AppKey}}, &ap)
}
